<template>
  <div class="order-card">
    <!-- 商品列表 -->
    <div v-for="(item, index) in orders" class="order-item">
      <div class="order-id" v-if="isFirstOfSameGroup(index)">
        <p>订单号：{{ item.order_number }}</p>
        <p>下单时间：{{ formatOrderTime(item.order_time) }}</p>
        <p>订单总价：￥{{ item.totalPrice }}</p>
      </div>
      <div class="item-info">
        <div class="item-image">
          <img :src="getServerUrl()+'media/dishes/'+item.img" alt="item.name"/>
          <p class="item-name">{{ item.name }}</p>
        </div>
        <p>{{ item.status }}</p>
      </div>

      <div class="item-details">
        <p class="item-price">¥{{ item.price }} x {{ item.goods_num }}</p>
      </div>

      <!-- 单个订单总价 -->
      <div class="order-total">
        <p>总价：<span class="total-price">¥{{ itemTotalPrice(item) }}</span></p>
      </div>

      <!-- 倒计时显示 -->
      <div class="order-countdown" v-if="isLastOfSameGroup(index) && item.sta === 0">
        <p v-if="item.remainingTime > 0">请在 {{ formatCountdown(item.remainingTime) }} 内完成支付</p>
        <p class="order-timeout" v-else>订单已超时未支付</p>
      </div>


      <!-- 操作按钮 -->
      <div class="order-actions" v-if="isLastOfSameGroup(index)">
        <van-button @click="backShopCar(item.id)" v-if="item.sta > -10">返回购物车</van-button>
        <van-button @click="pay(item.order_number,item.totalPrice)" v-if="item.sta === 0">前往付款</van-button>
        <van-button @click="confirmReceipt(item.id,item.sta)" v-if="item.sta === 1">确认收货</van-button>
        <van-button @click="evaluateOrder(item.id)" v-if="item.sta === 2">前往评价</van-button>
        <van-button @click="wcorder(item.id)" v-if="item.sta === 3">删除订单</van-button>
        <van-button @click="cancelOrder(item.id,item.totalPrice,item.sta)" v-if="item.sta === 0">取消订单</van-button>
      </div>

    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, onBeforeUnmount, defineEmits, defineProps} from 'vue';
import requestUtil, {getServerUrl} from "@/utils/request.js";
import {ElMessage} from "element-plus";
import Cookies from "js-cookie";
import {useRouter} from "vue-router";

let router = useRouter();
// 接收父组件传递的 orders 数据
const props = defineProps({
  orders: {
    type: Array,
    required: true,
  },
});
const evaluateOrder = (id) => {
  router.push({
    path: '/publishUpdates',
    query: {
      orderId: id
    }
  })
};

const emit = defineEmits(['refreshOrders']);
const confirmReceipt =async (orderId,status) => {
  let res = await requestUtil.post('/app/updateOrderStatus/', {
    orderId: orderId,
    userId: Cookies.get('userId'),
    status: status,
  });
  if (res.data.code === 200) {
    ElMessage.success("确认收货成功");
      emit('refreshOrders'); // 通知父组件刷新数据
  } else {
    ElMessage.error("确认收货失败");
  }
}

// 定义倒计时逻辑
function startCountdown() {
  setInterval(() => {
    props.orders.forEach((item) => {
      if (item.sta === 0) { // 只更新未支付订单的倒计时
        const now = new Date().getTime();
        const orderTime = new Date(item.order_time).getTime();
        const elapsed = Math.floor((now - orderTime) / 1000);
        item.remainingTime = Math.max(300 - elapsed, 0);
      }
    });
  }, 1000);
}


const cancelOrder = async (orderId, totalPrice,status) => {
  let res = await requestUtil.post('/app/cancelOrder/', {
    orderId: orderId,
    userId: Cookies.get('userId'),
    totalPrice: totalPrice,
  });
  if (res.data.code === 200) {
    ElMessage.success("取消订单成功");

    const order = props.orders.find((order) => order.id === orderId);
    if (order) {
      let res = await requestUtil.post('/app/updateOrderStatus/', {orderId: orderId,userId: Cookies.get('userId'),status:status})
      order.remainingTime = -1; // 停止倒计时
      emit('refreshOrders'); // 通知父组件刷新数据
    }
  } else {
    ElMessage.error("取消订单失败");
  }
};

const pay = (orderNumber, totalPrice) => {
  window.sessionStorage.setItem('totalPrice', totalPrice)
  router.push({
    path: '/pay',
    query: {
      orderNumber: orderNumber
    }
  })
}

// 格式化倒计时
function formatCountdown(seconds) {
  const minutes = String(Math.floor(seconds / 60)).padStart(2, '0');
  const secs = String(seconds % 60).padStart(2, '0');
  return `${minutes}:${secs}`;
}

// 格式化下单时间
function formatOrderTime(orderTime) {
  const date = new Date(orderTime);
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 ${date.toLocaleTimeString()}`;
}

// 判断当前订单是否是同组的第一个
function isFirstOfSameGroup(index) {
  if (index === 0) return true;
  return props.orders[index].order_number !== props.orders[index - 1].order_number;
}

// 判断当前订单是否是同组的最后一个
function isLastOfSameGroup(index) {
  return (
      index === props.orders.length - 1 || props.orders[index].order_number !== props.orders[index + 1].order_number
  );
}

// 计算单个订单的总价
function itemTotalPrice(item) {
  return (item.price * item.goods_num).toFixed(2);
}

// 初始化倒计时
onMounted(() => startCountdown());
onBeforeUnmount(() => clearInterval());
</script>

<style scoped>
.order-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
  background: linear-gradient(135deg, #ffffff, #f0f4f8); /* 渐变背景色 */
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.order-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.15);
  background: linear-gradient(135deg, #f0f4f8, #e8eef3); /* 悬停时加深背景渐变 */
}


.order-item {
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e0e0e0;
}

.item-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-image {
  display: flex;
  align-items: center;
}

.item-image img {
  width: 100px;
  height: 100px;
  border-radius: 5px;
  margin-right: 10px;
}

.item-image p {
  font-size: 30px;
}

.item-details {
  flex: 1;
}

.item-name {
  font-size: 16px;
  font-weight: bold;
}

.item-price {
  color: #666;
}

.order-total {
  margin-top: 5px;
  font-size: 30px;
  text-align: right;
  font-weight: bold;
}

.total-price {
  color: #ff4d4f;
}

.order-countdown {
  margin-top: 10px;
  font-size: 14px;
  color: #f56c6c;
}

.order-actions {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}
.order-actions button {
  margin-left: 8px;
  color: white;
  background: linear-gradient(90deg, #38b2ac, #319795);
  border-radius: 25px;
  padding: 8px 12px;
  font-size: 30px;
  font-weight: 600;
  transition: all 0.3s ease;
  border: none;
}

.order-actions button:hover {
  background: linear-gradient(90deg, #2c7a7b, #285e61);
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.1);
}

.order-timeout {
  font-size: 20px;
}
</style>
